/**
 * Created by S on 2016/3/21.
 */
var fs = require('fs');

//响应格式
exports.ResponseFormat = function (err, data) {
    var responseData = {};
    if (err) {
        responseData = {
            status: 500,
            exception: err
        }
    } else {
        if (typeof data == "object" && data.length) {
            responseData = {
                status: 200,
                recordset: data
            }
        } else {
            responseData = {
                status: 200,
                recordset: data
            }
        }
    }
    return JSON.stringify(JSON.stringify(responseData));
}

/**//**
 * 检查输入的字符是否具有特殊字符
 * 输入:str  字符串
 * 返回:true 或 flase; true表示包含特殊字符
 * 主要用于注册信息的时候验证
 */
exports.checkQuote=function(str){
    var items = new Array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "{", "}", "[", "]", "(", ")");
    items.push(":", ";","\"", "'", "|", "\\\\", "<", ">", "?", "/", "<<", ">>", "||", "//");
    str = str.toLowerCase();
    for (var i = 0; i < items.length; i++) {
        if (str.indexOf(items[i]) >= 0) {
            return true;
        }
    }
    return false;
}

//form表达回答
exports.answer=function(res,msg,url)
{
    res.writeHead(200, {'content-type': 'text/html;charset=utf-8'});
    res.write("<!DOCTYPE html><html><head><title></title></head><body onload=\"alert('"+ msg + "');window.location.href='" + url + "'\"\></body></html>");
    res.end();
}

timedCount();
setInterval(timedCount,12*60*60*1000);
function timedCount() {
    deleteerr();
}
//删除无用文件
function deleteerr()
{
    var filesList = geFileList("./public/files/");
    for(var i=0;i<filesList.length;i++)
    {
        var item = filesList[i];
        var desc ="";
        desc=item.name;// + " " +"大小:"+(item.size/1024).toFixed(2) +"/kb";
        if(desc.indexOf('.')<=0)
        {
            deleteFile(desc);
        }
    }
}

function geFileList(path)
{
    var filesList = [];
    readFile(path,filesList);
    return filesList;
}

//遍历读取文件
function readFile(path,filesList)
{
    files = fs.readdirSync(path);//需要用到同步读取
    files.forEach(walk);
    function walk(file)
    {
        states = fs.statSync(path+'/'+file);
        if(states.isDirectory())
        {
            readFile(path+'/'+file,filesList);
        }
        else
        {
            //创建一个对象保存信息
            var obj = new Object();
            obj.size = states.size;//文件大小，以字节为单位
            obj.name = file;//文件名
            obj.path = path+'/'+file; //文件绝对路径
            filesList.push(obj);
        }
    }
}

function deleteFile(name)
{
    // 获取a文件夹的类型
    fs.stat('./public/files/'+name,function(err, stat){
        if(err){
            console.log("删除文件不存在！");
        }else{
            if(stat.isFile())
            {
                //fs.unlink(path[,callback]);//或者
                fs.unlinkSync('./public/files/'+name);
                console.log('delete:'+name);
            }
        }
    });
}

exports.deleteFile=function(name)
{
    deleteFile(name);
}
